package org.example.Polls;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class PollAdapter extends BaseAdapter {
	private Context context;
	
	private List<Poll> pollList;
	
	public PollAdapter(Context context, List<Poll> pollList) {
		this.context = context;
		this.pollList = pollList;
	}
	
	public int getCount() {
		return pollList.size();
	}

	public Object getItem(int position) {
		return pollList.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup viewGroup) {
		Poll entry = pollList.get(position);
		if(convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			convertView = inflater.inflate(R.layout.poll_row, null);
		}
		TextView pollTitle = (TextView) convertView.findViewById(R.id.poll_row_title);
		pollTitle.setText(entry.getTitle());
		
		TextView pollCreator = (TextView) convertView.findViewById(R.id.poll_row_creator_name);
		User admin = entry.getAdministrator();
    	pollCreator.setText(admin.getDisplayName(entry.getAnonymous()));
		
		TextView pollStatus = (TextView) convertView.findViewById(R.id.poll_row_status);
		pollStatus.setText(getStatus(entry));
		//TextView pollStart = (TextView) convertView.findViewById(R.id.poll_row_start_picked);
		//pollStart.setText(entry.getStartDate().toString());
		//TextView pollEnd = (TextView) convertView.findViewById(R.id.poll_row_end_picked);
		//pollEnd.setText(entry.getEndDate().toString());
		
		return convertView;
	}
	
	public String getStatus(Poll poll) {
        String status;
        Date now = new Date();
        if (poll.getStartDate().after(now)) {
        	status = "Starts in "+getApproximateTime(poll.getStartDate());
        } else if (poll.getEndDate().before(now)) {
        	status = "Finished "+getApproximateTime(poll.getEndDate())+" ago";
        } else {
        	status = getApproximateTime(poll.getEndDate())+" remaining";
        }
        return status;
	}
	
	public String getApproximateTime(Date date) {
        Date now = new Date();
		long millis = Math.abs(now.getTime()-date.getTime());
		
		StringBuffer sb = new StringBuffer();
		
		long days = millis / 86400000;
		if (days > 1)
			sb.append(days+" days");
		else {
			if (days == 1)
    			sb.append(days+" day, ");
    		long hours = ((millis % 86400000)/3600000);
    		if (hours > 1)
    			sb.append(hours+" hours");
    		else {
    			if (hours == 1)
        			sb.append(hours+" hour, ");
        		long minutes = (((millis % 86400000)%3600000)/60000);
        		sb.append(minutes+" minute(s)");
    		}
		}
		
		return sb.toString();
	}
}
